package com.tencent.cloud.iov.util;

import android.view.MotionEvent;
import android.view.View;

/**
 * @author showxiao
 * @date 2018/8/6
 */
public class ViewStateUtils {

    private static final float VIEW_ALPHA_PRESSED = 0.6f;
    private static final float VIEW_ALPHA_DISABLED = 0.6f;

    public static void setUpViewPressState(final View... views) {
        if (views != null) {
            for (final View view : views) {

                // 避免不可击状态透明度的配置，导致未正确获取初始透明度
                Object enabledAlphaObj = view.getTag(R.id.tag_view_alpha_enabled);
                final float defaultAlpha = (enabledAlphaObj != null) ? (float) enabledAlphaObj : 1.0f;

                view.setOnTouchListener(new View.OnTouchListener() {

                    private float mDefaultAlpha = defaultAlpha;

                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        switch (event.getAction()) {
                            case MotionEvent.ACTION_DOWN:
                                v.setAlpha(VIEW_ALPHA_PRESSED);
                                break;
                            case MotionEvent.ACTION_UP:
                            case MotionEvent.ACTION_CANCEL:
                                v.setAlpha(mDefaultAlpha);
                                break;
                        }
                        return false;
                    }
                });
            }
        }

    }

    public static void cancelViewPressState(final View... views){
        if (views != null){
            for (final View view : views){
                view.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View view, MotionEvent motionEvent) {
                        return false;
                    }
                });
            }
        }
    }

    public static void setUpViewEnableState(boolean enabled, final View... views) {
        if (views != null) {
            for (final View view : views) {
                // 保存原始透明度
                if (view.isEnabled() && view.getAlpha() < 1.0f) {
                    view.setTag(R.id.tag_view_alpha_enabled, view.getAlpha());
                }

                Object enabledAlphaObj = view.getTag(R.id.tag_view_alpha_enabled);
                float enabledAlpha = (enabledAlphaObj != null) ? (float) enabledAlphaObj : 1.0f;
                view.setAlpha(enabled ? enabledAlpha : enabledAlpha * VIEW_ALPHA_DISABLED);
            }
        }

    }

}
